import User from "../data/user";
// import {SchemaError} from "graphql-tools";

export async function findUser(userId) {
    try {
        let res = await User.find({userId: userId});
        return res;
    } catch (error) {
        console.log("findUserError:", error);
        // throw new SchemaError(error.message);
    }
}

export async function createUser(args = {}) {
    try {
        const checkUser = await findUser(args.userId);
        if (Array.isArray(checkUser) && checkUser.length > 0) {
            return checkUser;
        }
        let user = new User(args);
        const res = await user.save();
        return res;
    } catch (error) {
        console.log("createUserError:", error);
        // throw new SchemaError(error.message);
    }
}

export async function findUserList(args = {}) {
    try {
        const queryUser = await User.find(args);
        return {
            userList: queryUser
        };
    } catch (error) {
        console.log("findUserListError:", error);
        // throw new SchemaError(error.message);
    }
}

export async function updateUserRole(userId, role) {
    try {
        const res = await User.findOneAndUpdate({userId: userId}, {role: role}, {new: true});
        return res;
    } catch (error) {
        console.log("updateUserRoleError:", error);
        throw Error(error);
    }
}
